package com.yaukie.socket.config;

import com.yaukie.socket.constants.Constants;
import com.yaukie.socket.listener.RedisMessageListener;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Configuration
public class RedisConfig {


    @Bean
    public StringRedisTemplate stringRedisTemplate (RedisConnectionFactory factory ){
        return new StringRedisTemplate(factory);
    }

    @Bean("redisMessageListener")
    public RedisMessageListener redisMessageListener (){
        return new RedisMessageListener() ;
    }

    @DependsOn("redisMessageListener")
    @Bean
    public RedisMessageListenerContainer redisMessageListenerContainer (RedisConnectionFactory factory,
                                                                         RedisMessageListener redisMessageListener ){
        RedisMessageListenerContainer redisMessageListenerContainer = new RedisMessageListenerContainer() ;
        redisMessageListenerContainer.setConnectionFactory(factory);

        List topics = new LinkedList() ;

        Consumer<Topic> consumer = topics ::add;

        Topic CHAT_ROOM_N_01 = new ChannelTopic(Constants.CHAT_ROOM_N_01) ;
        consumer.accept(CHAT_ROOM_N_01);
        Topic CHAT_ROOM_N_02 = new ChannelTopic(Constants.CHAT_ROOM_N_02) ;
        consumer.accept(CHAT_ROOM_N_02);
        Topic CHAT_ROOM_N_03 = new ChannelTopic(Constants.CHAT_ROOM_N_03) ;
        consumer.accept(CHAT_ROOM_N_03);

        redisMessageListenerContainer.addMessageListener(redisMessageListener,topics);
        return redisMessageListenerContainer ;

    }

}
